<template>
  <div>
    <doc-alert title="【交易】快递发货" url="https://doc.iocoder.cn/mall/trade-delivery-express/" />

    <!-- 门店后台登录地址 -->
    <div class="flex items-center p-4 mb-4 bg-yellow-50 border border-yellow-200 rounded">
      <span class="inline-block px-2 py-1 mr-2 text-sm bg-gray-200 rounded">门店后台</span>
      <span class="mr-2">登录地址:</span>
      <code class="flex-grow text-sm text-gray-700">{{ storeLoginUrl }}</code>
      <el-button type="warning" size="small" @click="handleCopy(storeLoginUrl)">复制</el-button>
    </div>

    <!-- 搜索工作栏 -->
    <ContentWrap>
      <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="98px">
       <!-- ... existing form items ... -->
        <el-form-item label="门店名称" prop="name">
          <el-input
            v-model="queryParams.name"
            class="!w-240px"
            clearable
            placeholder="请输入门店名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="店铺手机号" prop="phone">
          <el-input
            v-model="queryParams.phone"
            class="!w-240px"
            clearable
            placeholder="请输入店铺手机号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="管理员手机号" prop="storeMgPhone">
          <el-input
            v-model="queryParams.storeMgPhone"
            class="!w-240px"
            clearable
            placeholder="请输入管理员手机号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="门店地址" prop="areaId">
          <el-cascader
            v-model="queryParams.areaId"
            :options="areaList"
            :props="cascaderProps"
            class="!w-240px"
            placeholder="请选择门店区域"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
           <el-button @click="resetQuery">
             <Icon class="mr-5px" icon="ep:refresh" />
             重置
           </el-button>
           <el-button plain type="warning" @click="handleExport">
             <Icon icon="ep:download" class="mr-5px" /> 导出
           </el-button>
          <el-button
            v-hasPermi="['trade:delivery:pick-up-store:create']"
            plain
            type="primary"
            @click="openForm('create')"
          >
            <Icon class="mr-5px" icon="ep:plus" />
            添加门店
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
       <div class="mb-10px">
         统计 门店总数: {{ total }} &nbsp;&nbsp;&nbsp; 入驻中: {{ settlingCount }} &nbsp;&nbsp;&nbsp; 已过期: {{ expiredCount }}
       </div>
      <el-table v-loading="loading" :data="list">
         <!-- ... existing table columns ... -->
         <el-table-column label="ID" min-width="80" prop="id" align="center"/>
        <el-table-column label="门店名称" min-width="200">
          <template #default="scope">
            <div class="flex items-center">
              <el-image
                :src="scope.row.logo"
                fit="cover"
                class="w-12 h-12 rounded mr-2 flex-shrink-0"
                preview-teleported
                :preview-src-list="[scope.row.logo]"
              >
                <template #error>
                  <div class="w-12 h-12 bg-gray-100 rounded mr-2 flex-shrink-0 flex items-center justify-center text-gray-400 text-xs">无图</div>
                </template>
              </el-image>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
         <el-table-column label="所在省市详细地址(门牌号)" min-width="250">
           <template #default="scope">
             <div>{{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district }}{{ scope.row.town }}</div>
             <div>{{ scope.row.detailAddress }}</div>
           </template>
         </el-table-column>
         <el-table-column label="管理员手机号" prop="storeMgPhone" min-width="150" align="center">
          <!-- 直接使用 prop 显示 storeMgPhone，或者保留 template 如果需要更复杂逻辑 -->
          <!--
            <template #default="scope">
              <div class="flex items-center">
                <div class="w-10 h-10 bg-orange-300 rounded-full mr-2 flex-shrink-0"></div>
                <span>{{ scope.row.managerPhone }}</span>
              </div>
            </template>
          -->
         </el-table-column>
         <el-table-column label="经营状态" align="center" prop="status" min-width="100">
           <template #default="scope">
             <el-tag :type="formatOperatingStatusType(scope.row.status)">
               {{ formatOperatingStatusText(scope.row.status) }}
             </el-tag>
           </template>
         </el-table-column>
         <el-table-column label="累计实收金额" min-width="150" align="center">
           <template #default="scope">
             <div>收银台: {{ formatCurrency(scope.row.totalCashierAmount) }}</div>
             <div>门店: {{ formatCurrency(scope.row.totalStoreAmount) }}</div>
           </template>
         </el-table-column>
         <el-table-column label="未结算金额" min-width="150" align="center">
           <template #default="scope">
             <div>收银台: {{ formatCurrency(scope.row.unsettledCashierAmount) }}</div>
             <div>门店: {{ formatCurrency(scope.row.unsettledStoreAmount) }}</div>
           </template>
         </el-table-column>
         <el-table-column label="门店小程序码" min-width="110" align="center">
           <template #default="scope">
             <el-image
               v-if="scope.row.wxaQrcode"
               :src="scope.row.wxaQrcode"
               fit="contain"
               lazy
               class="w-10 h-10 rounded"
               preview-teleported
               :preview-src-list="[scope.row.wxaQrcode]"
             />
             <el-button v-else link type="primary" @click="handleGenerateQrCode(scope.row)" :loading="scope.row.qrLoading">
               生成
             </el-button>
           </template>
         </el-table-column>
        <el-table-column align="center" label="操作" min-width="110" fixed="right">
          <template #default="scope">
            <el-button
              v-hasPermi="['trade:delivery:pick-up-store:update']"
              link
              type="primary"
              @click="openSetForm('update', scope.row.id)"
            >
              设置
            </el-button>
            <el-button
              v-hasPermi="['trade:delivery:pick-up-store:update']"
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPermi="['trade:delivery:pick-up-store:delete']"
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
         :total="total"
         v-model:page="queryParams.pageNo"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
       />
    </ContentWrap>

    <!-- 表单弹窗：添加/修改 -->
    <DeliveryPickUpStoreForm ref="formRef" @success="getList" />
    <DeliveryPickUpStoreSetForm ref="setFormRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import * as DeliveryPickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore/index' // 导入 API
import type { StoreWxQrReqVO } from '@/api/mall/trade/delivery/pickUpStore/index' // 导入类型
import DeliveryPickUpStoreForm from './PickUpStoreForm.vue' // 导入表单组件
import DeliveryPickUpStoreSetForm from './PickUpStoreSetForm.vue' // 导入表单组件
import { formatDate } from '@/utils/formatTime' // 导入时间格式化函数
import { getAreaTree } from '@/api/system/area' // Area API
// import type { AreaVO } from '@/api/system/model/areaModel' // Correct AreaVO import
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps } from '@/utils/tree'
import { getTenantId } from '@/utils/auth'

 const message = useMessage() // Utilities
 const { t } = useI18n()

 // --- Refs and Reactive Variables ---
 const total = ref(0)
 const settlingCount = ref(0)
 const expiredCount = ref(0)
 const loading = ref(true)
 const list = ref<DeliveryPickUpStoreApi.DeliveryPickUpStoreVO[]>([]) // 添加类型

 // 门店后台登录地址 (计算属性)
 const storeLoginUrl = computed(() => {
   const baseUrl = import.meta.env.VITE_APP_STORE_LOGIN_URL
   const tenantId = getTenantId();
   if (!baseUrl) {
     return '未配置登录地址'
   }
   // 确保 tenantId 存在且不为空
   if (tenantId) {
     // 检查 baseUrl 是否已包含查询参数
     const separator = baseUrl.includes('?') ? '&' : '?'
     return `${baseUrl}${separator}tenant-id=${tenantId}`
   }
   // 如果没有 tenantId，则只返回基础 URL
   return baseUrl
 })

 const formRef = ref() // Ref for DeliveryPickUpStoreForm
 const setFormRef = ref() // Ref for DeliveryPickUpStoreForm
 const queryFormRef = ref() // Ref for the search form
 const areaList = ref<any[]>([]) // Region data
 const cascaderProps = {
   value: 'id', // ID field name
   label: 'name', // Name field name
   children: 'children', // Child node field name
   checkStrictly: false, // Allow selecting any level
   emitPath: false // Only return the selected node's ID
 }

 // Search Query Parameters
 const queryParams = reactive({
   pageNo: 1,
   pageSize: 10,
   name: undefined,
   shopkeeperUserId: undefined,
   shopkeeperInfo: undefined,
   bossUserId: undefined,
   bossInfo: undefined,
   category: undefined,
   settleStatus: undefined,
   isChain: undefined,
   areaId: undefined,
   settleTime: [],
   inBlacklist: undefined,
   phone: undefined,
   storeMgPhone: undefined
 })

 // --- Methods ---

 /** Query List */
 const getList = async () => {
   loading.value = true
   try {
     // 使用新的 API 函数
     const data = await DeliveryPickUpStoreApi.getDeliveryPickUpStorePage(queryParams)
     list.value = data.list.map(item => ({ ...item, qrLoading: false }))
     total.value = data.total
     settlingCount.value = data.settlingCount || 0 // Use defaults if not provided
     expiredCount.value = data.expiredCount || 0 // Use defaults if not provided
   } finally {
     loading.value = false
   }
 }

 /** Handle Search */
 const handleQuery = () => {
   queryParams.pageNo = 1
   getList()
 }

 /** Reset Search */
 const resetQuery = () => {
   queryFormRef.value.resetFields()
   // Also reset non-form fields if necessary
   queryParams.areaId = undefined
   handleQuery()
 }

 /** Handle Export */
 const handleExport = () => {
    console.log('执行导出, 参数:', JSON.parse(JSON.stringify(queryParams)))
    message.success('导出功能暂未实现')
 }

 /** Open Add/Edit Form */
 const openForm = (type: string, id?: number) => {
   formRef.value.open(type, id)
 }
 /** Open Add/Edit Form */
 const openSetForm = (type: string, id?: number) => {
   setFormRef.value.open(type, id)
 }
 /** Delete Operation */
 const handleDelete = async (id: number) => {
   try {
     // 删除的二次确认
     await message.delConfirm()
     // 发起删除
     await DeliveryPickUpStoreApi.deleteDeliveryPickUpStore(id)
     message.success(t('common.delSuccess'))
     // 刷新列表
     await getList()
   } catch (error) {
     // 如果用户取消了确认框，delConfirm 会 reject，通常不需要特别处理
     // 如果是 API 调用失败，可以添加错误提示
     console.error("删除操作失败:", error);
     // 可根据需要添加 message.error('删除失败');
   }
 }

 /** Copy Text */
 const handleCopy = async (text: string) => {
   try {
     await navigator.clipboard.writeText(text)
     message.success('复制成功！')
   } catch (err) {
     message.error('复制失败: ' + err)
   }
 }

 /** 生成并显示门店小程序码 */
 const handleGenerateQrCode = async (row: DeliveryPickUpStoreApi.DeliveryPickUpStoreVO & { qrLoading?: boolean }) => {
   if (!row || !row.id) {
     message.error('无法获取门店信息');
     return;
   }
   // 设置加载状态
   row.qrLoading = true;
   try {
     const params: StoreWxQrReqVO = {
       id: row.id,
       scene: `storeId=${row.id}`, // 使用门店ID作为场景值
       path: `pages/index/index`, // 默认路径 (如果需要配置，可以修改这里)
       width: 430,
       autoColor: true,
       checkPath: false,
       hyaline: false
     };
     const qrCodeBase64 = await DeliveryPickUpStoreApi.generateStoreWxaQrCode(params);
     if (qrCodeBase64) {
       message.success('小程序码生成成功，正在刷新列表...');
       await getList(); // Refresh the list to show the new QR code
     } else {
       message.error('获取二维码失败');
     }
   } catch (error) {
     console.error("生成二维码失败:", error);
     message.error('生成二维码时出错');
   } finally {
     // 取消加载状态
     row.qrLoading = false;
   }
 }

 // --- Formatting Functions ---
 const formatTime = (time) => {
   return time ? time.substring(0, 10) : ''
 }

 const formatCurrency = (amount) => {
   if (amount === null || amount === undefined) return '0.00'
   return Number(amount).toFixed(2)
 }

 const formatOperatingStatusText = (status) => {
   switch (status) {
     case 0: return '营业';
     case 1: return '休息';
     default: return '未知';
   }
 };

 const formatOperatingStatusType = (status) => {
   switch (status) {
     case 0: return 'success'; // 营业 - 绿色
     case 1: return 'info';    // 休息 - 灰色 (or 'danger' if preferred)
     default: return 'info';
   }
 };

 // --- Lifecycle Hooks ---
 onMounted(() => {
   getList()
   loadAreaTree() // Load area data on mount
 })

 const loadAreaTree = async () => {
   try {
     const rawData = await getAreaTree()
     if (rawData && rawData.length > 0) {
       // API already returns a tree, no need for handleTree
       areaList.value = rawData;
     } else {
       console.warn('No area data received from API.')
       areaList.value = []
     }
   } catch (error) {
     console.error('Failed to load or process area tree:', error)
     areaList.value = []
   }
 }
</script>
